package com.mx.zb.mng.ctrl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mx.zb.mng.bo.Agent;
import com.mx.zb.mng.bo.AgentLevel;
import com.mx.zb.mng.bo.Module;
import com.mx.zb.mng.bo.Operator;
import com.mx.zb.mng.bo.RechargeCount;
import com.mx.zb.mng.bo.Role;
import com.mx.zb.mng.bo.RoleModuleRela;
import com.mx.zb.mng.bo.Tenant;
import com.mx.zb.mng.cache.IncCounter;
import com.mx.zb.mng.cache.OperatorCaches;
import com.mx.zb.mng.dao.AgentLevelMapper;
import com.mx.zb.mng.dao.AgentMapper;
import com.mx.zb.mng.dao.ModuleMapper;
import com.mx.zb.mng.dao.OperatorMapper;
import com.mx.zb.mng.dao.RechargeCountMapper;
import com.mx.zb.mng.dao.RoleMapper;
import com.mx.zb.mng.dao.RoleModuleRelaMapper;
import com.mx.zb.mng.dao.TenantMapper;
import com.mx.zb.mng.utils.AjaxResult;
import com.mx.zb.mng.utils.Constant;
import com.mx.zb.mng.utils.Crypt;
import com.mx.zb.mng.utils.DateUtil;
import com.mx.zb.mng.utils.UnionCode;
import com.mx.zb.mng.utils.context.ContextThread;
import com.mx.zb.mng.utils.db2.Page;
import com.mx.zb.mng.utils.db2.PageHelper;

/**
 * 
 * @ClassName: AgentRestCtrl
 * @Description: 代理商
 * @author 李志伟
 * @date 2017年9月22日 下午10:11:12 
 *
 */
@RestController
@RequestMapping("/a/biz")
public class AgentRestCtrl {
	
	@Autowired
	IncCounter incCounter;
	@Autowired
	AgentMapper agentMapper;
	
	@Autowired
	OperatorMapper operatorMapper;
	
	@Autowired
	RoleMapper roleMapper;
	
	@Autowired
	ModuleMapper moduleMapper;
	
	@Autowired
	TenantMapper tenantMapper;
	@Autowired
	OperatorCaches operatorCaches;
	
	@Autowired
	RoleModuleRelaMapper roleModuleRelaMapper;
	@Autowired
	AgentLevelMapper agentLevelMapper;
	@Autowired
	RechargeCountMapper rechargeCountMapper;
	
	Logger log = LoggerFactory.getLogger(this.getClass());
	
	
	@RequestMapping(value= {"/agent"}, method= {RequestMethod.PUT})
	@Transactional
	public AjaxResult save(@RequestBody JSONObject params) {
		Agent o=params.getObject("agent",Agent.class);
		Agent a=agentMapper.findByPhone(o);
		if(a!=null) {
			return new AjaxResult().failure("电话号码不能重复，请修改");
		}
		
		AgentLevel alevel=agentLevelMapper.selectByPrimaryKey(o.getLevelId());
		if(alevel.getMinCount()-o.getTotalCount()>0) {
			return new AjaxResult().failure("代理套数要大于等于代理商级别的套数，请修改");
		}

		String userId= ContextThread.get().getOperatorId();//当前登录人id
		Integer maxTenantCode=incCounter.getMaxAgentCode();//代理商编码
		
		
		String parentAgentId= ContextThread.get().getAgentId();//当前代理商ID
		Agent  parentAgent=agentMapper.selectByPrimaryKey(parentAgentId);//当前代理商
		String type=parentAgent.getType();
		if(!Constant.headquarters.equals(type.trim())&&parentAgent.getLeftCount()-o.getTotalCount()<0) {
			return new AjaxResult().failure("代理套数不能大于上级代理剩余套数，请修改");
		}
		
		if(!Constant.headquarters.equals(type.trim())&&parentAgent.getLeftCount()==0) {
			return new AjaxResult().failure("上级代理商剩余套数为0，不能创建代理商");
		}
		
		
		String agentId=UnionCode.getShortUuid();
		
		String levelCode=parentAgent.getLevelCode();

		int n = levelCode.length()+4;//取出字符串的长度
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("codeLength", n);
		map.put("levelCode", levelCode);
		levelCode=agentMapper.queryMaxLevelCode(map);
		 int num=0;
		if(levelCode!=null) {
	     num = Integer.parseInt(levelCode)+1;//将该数字加一
	     levelCode = String.format("%0"+n+"d", num);         
		}else {
			levelCode=parentAgent.getLevelCode()+"0001";
		}
		
		if(levelCode.length()>40) {
			return new AjaxResult().failure("分销商不能超过10级");

		}
		
		saveAgent( o, agentId, maxTenantCode, userId,parentAgent,levelCode);
		
		String roleId=UnionCode.getShortUuid();
		/*默认给该agentId一个管理员角色*/
		 saveRole(roleId, agentId, userId);

		/*默认给该agentId一个管理员账号*/
		Operator creater=params.getObject("operater",Operator.class);
		String operatorId=UnionCode.getShortUuid();
		saveOperator( creater, operatorId, agentId, roleId, maxTenantCode, userId) ;

		saveOperator( o, agentId, roleId, userId) ;
		
		return new AjaxResult().success();
	}
	
	@RequestMapping(value= {"/agent"}, method= {RequestMethod.POST})
	@Transactional
	public AjaxResult update(@RequestBody JSONObject params) {
		Agent o=params.getObject("agent",Agent.class);
		String templateId=o.getTemplateId();
		if(templateId!=null) {
			if(templateId.contains("["))
			templateId=templateId.substring(1,templateId.length()-1);
		}
		o.setTemplateId(templateId);
		o.setUpdateDate(new Date());
		o.setUpdateOper(ContextThread.get().getOperatorId());
		agentMapper.updateByPrimaryKeySelective(o);
		return new AjaxResult().success();
	}
	
	@RequestMapping(value= {"/agent"}, method= {RequestMethod.DELETE})
	@Transactional
	public AjaxResult delete(@RequestBody Agent o) {
		/*if(o.getId().equals(ContextThread.get().getAgentId())) {
			return new AjaxResult().failure("代理商不能删自己的账号");
		}*/
		Agent pojo=agentMapper.selectByPrimaryKey(o.getId());
		String active=pojo.getIsActive();
		if("0".equals(active)) {
			o.setIsActive("1");
		}else {
			o.setIsActive("0");
		}
		agentMapper.updateByPrimaryKeySelective(o);
		
		return new AjaxResult().success();
	}
	/**代理商转移如果是转移到自己下属（list有数据）则需要将自己直接下属的parentId变成自己的上级**/
	@RequestMapping(value= {"/updateZyAgent"}, method= {RequestMethod.POST})
	@Transactional
	public AjaxResult updateZyAgent(@RequestBody Agent o) {
		//Agent pojo=getParent(o,o.getId());
		Agent pojo=getParent(o.getParentId() ,o.getId());
		if(pojo!=null) {
			Agent agent=agentMapper.selectByPrimaryKey(o.getId());
			pojo.setParentId(agent.getParentId());
			agentMapper.updateByPrimaryKeySelective(pojo);
		}
		o.setUpdateDate(new Date());
		o.setUpdateOper(ContextThread.get().getOperatorId());
		agentMapper.updateByPrimaryKeySelective(o);
		return new AjaxResult().success();
	}
	
	/**
	 * id的parentId是否是tid，递归到parentId为null
	 * @param id	转移到的代理商id
	 * @param tid	待转移的代理商id
	 * @return
	 */
	private Agent getParent(String id,String tid) {
    	Agent agent= agentMapper.selectByPrimaryKey(id); 
    	if(agent==null) {
    		return null;
    	}else {
    		
    		String pid = agent.getParentId();
    		
    		if(StringUtils.hasText(pid)) {
    			
    			if(pid.equals(tid)) {
    				return agent;
    			}else {
    				return getParent(pid, tid);
    			}
    			
    		}else {
    			return null;
    		}
    		
    	}
        
	} 
	
	   private Agent getParent(Agent o,String id) {
	        	Agent agent= agentMapper.selectByPrimaryKey(o.getParentId()); 
	        	if(agent==null) {
	        		return null;
	        	}
	            if (id.equals(agent.getParentId())) {//相等，则代表是他的上级  
	            	return agent;
	            }else {
	            	Agent pojo=getParent(agent,id);
	            	return pojo;
	            }  
	    }  
	
	
	@RequestMapping(value= {"/agents"}, method= {RequestMethod.GET})
	public AjaxResult getList() {
		String agentId=ContextThread.get().getAgentId();
		Agent o = new Agent();
		
//		o.setTenantId();
		String search = ContextThread.get().getSearch();
		if(search!=null&&search!="") {
			try{
				o= JSON.parseObject(search,Agent.class) ;
				if(o.getUpdateDate()!=null) {
				Calendar c=Calendar.getInstance();  
				c.setTime(o.getUpdateDate());
				c.add(Calendar.DATE, 1); 
				o.setUpdateDate(c.getTime());}
				}catch(Exception e) {
					e.printStackTrace();
					o = new Agent();

			}
		}
		if(!"dgd+Hy6G45Kab1uqE9yPLW".equals(agentId)) {//如果非总部，则添加条件，否则，查询所有
			o.setParentId(agentId);
		}
		PageHelper.startPage();
		Page<Agent> pages = agentMapper.queryPage(o);
		//将上级姓名暂时存在updateOper中以供页面显示
		if(pages!=null) {
			for (Agent p :pages) {
				String parentId=p.getParentId();
				p.setUpdateOper("");
				if(StringUtils.hasText(parentId)) {
					Agent agent=agentMapper.selectByPrimaryKey(parentId);
					if(agent!=null) {
						p.setUpdateOper(agent.getName());
					}
				}
			}
		}
		return new AjaxResult().success(pages);
	}
	
	//转移弹框的列表
	@RequestMapping(value= {"/agentList"}, method= {RequestMethod.GET})
	public AjaxResult getAgentList(Agent o) {
		PageHelper.startPage();
		Page<Agent> pages = agentMapper.queryPage1(o);
		
		return new AjaxResult().success(pages);
	}
	
	
	private void saveAgent(Agent o,String agentId,Integer maxTenantCode,String userId,Agent parentAgent,String levelCode) {
	
		
		o.setId(agentId);
		o.setAgentCode(maxTenantCode);
		o.setParentId(parentAgent.getId());
		o.setLevelCode(levelCode);
		o.setLeftCount(o.getTotalCount());
		String templateId=o.getTemplateId();
		if(templateId!=null) {
			if(templateId.contains("["))
			templateId=templateId.substring(1,templateId.length()-1);
		}
		o.setIsActive("1");
		o.setTemplateId(templateId);
		o.setCreateDate(new Date());
		o.setUpdateDate(o.getCreateDate());
		o.setCreateOper(userId);
		o.setUpdateOper(userId);
		agentMapper.insert(o);
		
		/*开了代理套数后当前代理商要减去开的套数*/
		String type=parentAgent.getType();
		if(!Constant.headquarters.equals(type.trim())) {
			parentAgent.setLeftCount(parentAgent.getLeftCount()-o.getTotalCount());
			agentMapper.updateByPrimaryKeySelective(parentAgent);
		}
		
		
	}
	
	
	private void saveRole(String  roleId,String agentId,String userId) {
		Role role=new Role();
		role.setId(roleId);
		role.setAgentId(agentId);
		role.setName(Constant.admin);
		role.setCreateDate(new Date());
		role.setUpdateDate(new Date());
		role.setCreateOper(userId);
		role.setUpdateOper(userId);
		roleMapper.insert(role);
	}
	
	
	private void saveOperator(Operator creater,String operatorId,String agentId,String roleId,Integer maxTenantCode,String userId) {
		creater.setId(operatorId);
		String enPass= Crypt.enAes(creater.getPassword());
		creater.setPassword(enPass);
		creater.setCreateDate(new Date());
		creater.setUpdateDate(new Date());
		creater.setCreateOper(userId);
		creater.setUpdateOper(userId);
		creater.setTenantCode(new Long(maxTenantCode));
		creater.setRoleId(roleId);
		creater.setName(Constant.admin);
		creater.setAgentId(agentId);
		operatorMapper.insert(creater);
	}
	
	
	private void saveOperator(Agent o,String agentId,String roleId,String userId) {

		String type=o.getType();
		int[] roleSets=new int[2];
		roleSets[0]=1;
		if(Constant.general.equals(type)) {
			roleSets[0]=1;
		}else if(Constant.distributor.equals(type)){
			roleSets[0]=1;
			roleSets[1]=3;

		}
		 List<Module> list=moduleMapper.selectByRoleSet(roleSets);
		 if(list!=null&&list.size()>0) {
			 for(Module module:list) {
				RoleModuleRela pojo=new RoleModuleRela();
				pojo.setRoleId(roleId);
				pojo.setModuleId(module.getId());
				pojo.setAgentId(agentId);
				pojo.setCreateDate(new Date());
				pojo.setUpdateDate(new Date());
				pojo.setCreateOper(userId);
				pojo.setUpdateOper(userId);
				roleModuleRelaMapper.insert(pojo);
			 }
		 }
		 
	}
	
	
	//获取所能代理商商户的套数
	@RequestMapping(value= {"/agent/getCount"}, method= {RequestMethod.POST})
	@Transactional
	@ResponseBody
	public AjaxResult  getUpAgentCount(@RequestParam String code,Model mo) {
		String agentId=ContextThread.get().getAgentId();
		if(agentId.equals(code)) {
			return new AjaxResult().failure("不能给自己充值,只能上级代理商充值");
		}
	/*Agent isZongBu = agentMapper.selectByPrimaryKey(agentId);
		if("总部".equals(isZongBu.getType())) {
			//可以给代理商,随意充值
		}*/
		Agent ag = agentMapper.selectByPrimaryKey(code);
		AgentLevel al = agentLevelMapper.selectByPrimaryKey(ag.getLevelId());
		al.getMinCount(); //代理最少套数
		Agent agt =new Agent();
		/*String lcode = ag.getLevelCode().substring(0,ag.getLevelCode().length()-4);
		agt.setLevelCode(lcode);*/
		agt = agentMapper.selectByPrimaryKey(agentId);
		if(agt==null) {
			return new AjaxResult().failure();
		}
		String type=agt.getType();
		
		agt.getLeftCount();//上级剩余套数
		int mc = 0;
		int lc = 0;
		mc = al.getMinCount();
		lc = Integer.parseInt(agt.getLeftCount().toString());
		if(lc<mc && !Constant.headquarters.equals(type)) {//上级总量不够
			mo.addAttribute("notCount", 0); //代理最少套数) //不能加
		}else if(Constant.headquarters.equals(type)) { //总部
			mo.addAttribute("notCount", 2);//随便加 
			mo.addAttribute("MinCount", mc); //代理最少套数)
			mo.addAttribute("LevelCode", lc);//上级剩余套数)
			mo.addAttribute("upAgentId", agt.getId());//上级
			
		}else {
		mo.addAttribute("notCount", 1); 
		mo.addAttribute("MinCount", mc); //代理最少套数)
		mo.addAttribute("LevelCode", lc);//上级剩余套数)
		mo.addAttribute("upAgentId", agt.getId());//上级
		}
		
		
		
		return new AjaxResult().success(mo);
	}
	
	//获取所能代理商商户的套数
	@RequestMapping(value= {"/agent/addCount"}, method= {RequestMethod.POST})
	@Transactional
	@ResponseBody
	public AjaxResult  addAgentCount(@RequestParam String code,String count,String upId,Model mo) {
		Agent agt =new Agent();
		agt.setId(code);
		agt =  agentMapper.findAgent(agt);
		agt.setTotalCount(agt.getTotalCount() + Long.parseLong(count));
		agt.setLeftCount( Long.parseLong(count)+ agt.getLeftCount() );
		agentMapper.updateByPrimaryKeySelective(agt);
		//减少上级代理数量
		
		Agent agt1 =new Agent();
		agt1.setId(upId);
		agt1 =  agentMapper.findAgent(agt1);
		if(agt1!=null&&!Constant.headquarters.equals(agt1.getType()) ) {
//		agt1.setTotalCount(agt1.getTotalCount() - Long.parseLong(count));
		agt1.setLeftCount( agt1.getLeftCount() -Long.parseLong(count)  );
		agentMapper.updateByPrimaryKeySelective(agt1);
		}
		//添加记录
		RechargeCount rc= new RechargeCount();
		rc.setAgentId(ContextThread.get().getAgentId());		
		rc.setCount(Long.parseLong(count));
		rc.setCreateDate(new Date());
		rc.setOperatorId(ContextThread.get().getOperatorId());
		rc.setToAgent(code);
		rc.setId(UnionCode.getShortUuid());
		rechargeCountMapper.insertSelective(rc);
		return new AjaxResult().success(mo);
		
	}
	@RequestMapping(value= {"/agentpwd"},method= {RequestMethod.PUT})
	public AjaxResult replacPwd(@RequestBody JSONObject jsonObject) {
		String id= jsonObject.getString("id");
		Agent pojo=agentMapper.selectByPrimaryKey(id);
		Operator op=new Operator();
		op.setAgentId(id);
		Integer agentCode=pojo.getAgentCode()==null?0:pojo.getAgentCode();
		op.setTenantCode(new Long(agentCode));
		Operator o=operatorMapper.selectByAgentId(op);
		o.setPassword(Crypt.enAes(Constant.replacePwd));
		operatorMapper.updateByPrimaryKey(o);
		return new AjaxResult().success();
	}

/*	获取数据库所有代理商的统计资料
	@SuppressWarnings({ "rawtypes" })
	@RequestMapping(value= {"/agentCal"})
	public AjaxResult agentCal(@RequestBody JSONObject jsonObject) {
	    Map map=new HashMap();
	    List<Agent> list1=agentMapper.findAgentGroupByDate(map);
	    List<Tenant> list2=tenantMapper.findTenantGroupByDate(map);
	    if(list1==null) {
	    list1=new ArrayList<Agent>();
	    }
	    if(list2==null) {
	    list2=new ArrayList<Tenant>();
	    }
	    List<Date> listDate=new  ArrayList<Date>();
	    for(Agent o: list1) {
	    	Date date=o.getCreateDate();
	    	if(!listDate.contains(date)) {
	    		listDate.add(date);
	    	}
	    }
	    for(Tenant o: list2) {
	    	Date date=o.getCreateDate();
	    	if(!listDate.contains(date)) {
	    	listDate.add(o.getCreateDate());
	    	}
	    }
	    Collections.sort(listDate);
	    map= calculation( list1,  list2, listDate);
	
		return new AjaxResult().success(map);
	}*/
	
/*	*********************总部首页统计************************************/	
	/*获取数据库最近一个月代理商商户的统计资料*/
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value= {"/agentCalByDay"})
	public AjaxResult agentCaloneMouth(@RequestBody JSONObject jsonObject) {
	    Map map=new HashMap();
	    List<Agent> list1=agentMapper.findAgentGroupByDate(map);
	    List<Tenant> list2=tenantMapper.findTenantGroupByDate(map);
	    int dlsSum=0;
        int shSum=0;
	    if(list1==null) {
	    list1=new ArrayList<Agent>();
	    }else {
	    	for(Agent agent:list1) {
				
				 dlsSum+=agent.getNums();
			
			}
	    }
	    if(list2==null) {
	    list2=new ArrayList<Tenant>();
	    }else {
	    	for(Tenant tenant:list2) {
				
	    		shSum+=tenant.getNums();
			
			}
	    }
	    Calendar cal = Calendar.getInstance();  
        cal.setTime(new Date()); 
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        cal.add(Calendar.MONTH, -1); 
        List<Date> listDate = DateUtil.getDatesBetweenTwoDate(cal.getTime(), new Date());  
         map= calculation( list1,  list2, listDate);
         map.put("dlsSum", dlsSum);
         map.put("shSum", shSum);
		return new AjaxResult().success(map);
	}
	
	/*获取数据库最近一年代理商商户的统计资料*/
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value= {"/agentCalByYear"})
	public AjaxResult agentCaloneYear(@RequestBody JSONObject jsonObject) {
	    Map map=new HashMap();
	    List<Map> listMap1=agentMapper.findAgentGroupByYear(map);
	    List<Map> listMap2=tenantMapper.findTenantGroupByYear(map);
	     List<Agent> list1=new ArrayList<Agent>();
	     List<Tenant> list2=new ArrayList<Tenant>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        int dlsSum=0;
        int shSum=0;
        try {
		if(listMap1!=null) {
			for(Map map1:listMap1) {
				String nums=map1.get("nums").toString();
				String createDate=map1.get("createDate").toString();
				 Agent agent=new Agent();
				 dlsSum+=new Integer(nums);
				agent.setNums(new Long(nums));
				agent.setCreateDate(sdf.parse(createDate));
				list1.add(agent);
			}
		}
		if(listMap2!=null) {
			for(Map map1:listMap2) {
				String nums=map1.get("nums").toString();
				String createDate=map1.get("createDate").toString();
				  Tenant tenant=new Tenant();
				tenant.setNums(new Long(nums));
				shSum+=new Integer(nums);
				tenant.setCreateDate(sdf.parse(createDate));
				list2.add(tenant);
			}
		}
    	} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	   
	    Calendar cal = Calendar.getInstance();  
        cal.setTime(new Date()); 
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        Date nowDate=cal.getTime();
        cal.add(Calendar.YEAR, -1); 
        List<Date> listDate = DateUtil.getMonthsBetweenTwoDate(cal.getTime(), nowDate);  
         map= calculation( list1,  list2, listDate);
         map.put("dlsSum", dlsSum);
         map.put("shSum", shSum);
		return new AjaxResult().success(map);
	}
	
	/*	*********************代理商统计************************************/	

	/*获取数据库最近一个月代理商商户的统计资料*/
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value= {"/tenatCalByMouth"})
	public AjaxResult tenatCalByMouth() {
	    Map map=new HashMap();
	    String agentId=ContextThread.get().getAgentId();
	    Agent agent= agentMapper.selectByPrimaryKey(agentId);
	   // map.put("levelCode", agent.getLevelCode());
	    map.put("agentId", agentId);
	    List<Tenant> list=tenantMapper.findTenantGroupByDate(map);
	    int num=0;
	 
	    if(list==null) {
	    	list=new ArrayList<Tenant>();
	    }else {
	    	for(Tenant tenant:list) {
	    		num+=tenant.getNums();
			}
	    }
	    Calendar cal = Calendar.getInstance();  
        cal.setTime(new Date()); 
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        cal.add(Calendar.MONTH, -1); 
        List<Date> listDate = DateUtil.getDatesBetweenTwoDate(cal.getTime(), new Date());  
         map= calculation( null,  list, listDate);
         map.put("num", num);
// 		Agent  agent=agentMapper.selectByPrimaryKey(agentId);//当前代理商
 		  map.put("leftCount", agent.getLeftCount());
 		  map.put("count", agent.getTotalCount()-agent.getLeftCount());
		return new AjaxResult().success(map);
	}
	
	
	/*获取数据库最近一年代理商商户的统计资料*/
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value= {"/tenatCalByYear"})
	public AjaxResult tenatCalByYear() {
	    Map map=new HashMap();
	    String agentId=ContextThread.get().getAgentId();
	    map.put("agentId", agentId);
	    Agent agent= agentMapper.selectByPrimaryKey(agentId);
	  //  map.put("levelCode", agent.getLevelCode());
	    List<Map> listMap=tenantMapper.findTenantGroupByYear(map);
	    List<Tenant> list=new ArrayList<Tenant>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        int num=0;
        try {
		if(listMap!=null) {
			for(Map map1:listMap) {
				String nums=map1.get("nums").toString();
				String createDate=map1.get("createDate").toString();
				  Tenant tenant=new Tenant();
				tenant.setNums(new Long(nums));
				num+=new Integer(nums);
				tenant.setCreateDate(sdf.parse(createDate));
				list.add(tenant);
			}
		}
    	} catch (ParseException e) {
			e.printStackTrace();
		}
	   
	    Calendar cal = Calendar.getInstance();  
        cal.setTime(new Date()); 
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        Date nowDate=cal.getTime();
        cal.add(Calendar.YEAR, -1); 
        List<Date> listDate = DateUtil.getMonthsBetweenTwoDate(cal.getTime(), nowDate);  
         map= calculation( null,  list, listDate);
         map.put("num", num);
//     	Agent  agent=agentMapper.selectByPrimaryKey(agentId);//当前代理商
		  map.put("leftCount", agent.getLeftCount());
		  map.put("count", agent.getTotalCount()-agent.getLeftCount());
		return new AjaxResult().success(map);
	}
	
	
	
	
	/*	*********************统计算法************************************/	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private Map calculation( List<Agent> list1, List<Tenant> list2,List<Date> listDate) {
	    for(Date date: listDate) {
	    	if(list1!=null) {
	    	Agent tmp=new Agent();
	    	if(list1.size()==0) {
	    		tmp.setCreateDate(date);
        		tmp.setNums(0L);
        		 list1.add(tmp );
	    	}else {
	    	if(date.getTime()<list1.get(0).getCreateDate().getTime()) {
	    		tmp.setCreateDate(date);
        		tmp.setNums(0L);
        		 list1.add(0, tmp);
	    	}else if(date.getTime()>list1.get(list1.size()-1).getCreateDate().getTime()) {
	    		tmp.setCreateDate(date);
        		tmp.setNums(0L);
        		 list1.add(tmp );
	    	}else {
	        for (int i=0;i<list1.size()-1;i++) {
	        	if(date.getTime()<list1.get(i+1).getCreateDate().getTime()&&
	        			date.getTime()>list1.get(i).getCreateDate().getTime()) {
		        		tmp.setCreateDate(date);
		        		tmp.setNums(0L);
		        		list1.add(i+1, tmp);
		        		break;
	        	}
	        }
	     } 
	    } 	
	   } 	
			Tenant tenantTmp=new Tenant();
	    	if(list2.size()==0) {
	    		tenantTmp.setCreateDate(date);
	    		tenantTmp.setNums(0L);
        		list2.add(tenantTmp );
	    	}else {
	    	if(date.getTime()<list2.get(0).getCreateDate().getTime()) {
	    		tenantTmp.setCreateDate(date);
	    		tenantTmp.setNums(0L);
        		 list2.add(0, tenantTmp);
	    	}else if(date.getTime()>list2.get(list2.size()-1).getCreateDate().getTime()) {
	    		tenantTmp.setCreateDate(date);
	    		tenantTmp.setNums(0L);
        		 list2.add(tenantTmp );
	    	}else {
	        for (int i=0;i<list2.size()-1;i++) {
	        	if(date.getTime()<list2.get(i+1).getCreateDate().getTime()&&
	        			date.getTime()>list2.get(i).getCreateDate().getTime()) {
	        		tenantTmp.setCreateDate(date);
		    		tenantTmp.setNums(0L);
	        		list2.add(i+1, tenantTmp);
	        		break;
	        	}
	        }
	      } 
	     }	
	    }
      
	   Map map=new HashMap();
	    map.put("list1", list1);
	    map.put("list2", list2);
	    map.put("listDate", listDate);
	    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  
	    if(list1!=null) {
	    for(Agent agent:list1) {
	    	if(agent.getNums()>0) {
	    		System.out.println(sdf.format(agent.getCreateDate())+"代理商开通数："+agent.getNums());
	    	}
	     }
	    } 
	    for(Tenant tenant:list2) {
	    	if(tenant.getNums()>0) {
	    		System.out.println(sdf.format(tenant.getCreateDate())+"商户开通数："+tenant.getNums());
	    	}
	    }
	    return map;
	}
	
	/******分销转普通，，需要将该代理商roleModuleRela所有权限为3的删掉********/
	
	@RequestMapping(value= {"/downType"},method= {RequestMethod.PUT})
	@Transactional
	public AjaxResult downType(@RequestBody Agent o) {
		o.setType(Constant.general);
		roleModuleRelaMapper.deleteBytAgentId(o.getId());
		agentMapper.updateByPrimaryKeySelective(o);
		List<Role> roles=roleMapper.findAllByAgent(o.getId());
		 if(roles!=null) {
		 for(Role role:roles) {
		operatorCaches.refreshSideBarList(role.getId());
		  }
		 } 
		return new AjaxResult().success();
	}

	/********普通转分销，需要将该代理商所有角色都添加到roleModuleRela**************/
	@RequestMapping(value= {"/upType"},method= {RequestMethod.PUT})
	@Transactional
	public AjaxResult upType(@RequestBody Agent o) {
		o.setType(Constant.distributor);
		String agentId=o.getId();
		List<Role> roles=roleMapper.findAllByAgent(agentId);
		int[] roleSets=new int[1];
		roleSets[0]=3;
		 List<Module> list=moduleMapper.selectByRoleSet(roleSets);
	    String operatorId=ContextThread.get().getOperatorId();
		 if(list!=null&&roles!=null) {
			 for(Module module:list) {
				 for(Role role:roles) {
				RoleModuleRela pojo=new RoleModuleRela();
				pojo.setRoleId(role.getId());
				pojo.setModuleId(module.getId());
				pojo.setAgentId(agentId);
				pojo.setCreateDate(new Date());
				pojo.setUpdateDate(new Date());
				pojo.setCreateOper(operatorId);
				pojo.setUpdateOper(operatorId);
				roleModuleRelaMapper.insert(pojo);
				operatorCaches.refreshSideBarList(role.getId());

				 }
			 }
		 }
		agentMapper.updateByPrimaryKeySelective(o);
		return new AjaxResult().success();
	}

	
	@RequestMapping(value= {"/detaiLAgents"}, method= {RequestMethod.GET})
	public AjaxResult getDetaiLists(Agent o) {
	
		PageHelper.startPage();
		Page<Agent> pages = agentMapper.queryDetailPage(o);
		
		return new AjaxResult().success(pages);
	}
	
	
	
	@RequestMapping(value= {"/countTenant"}, method= {RequestMethod.POST})
	public AjaxResult countTenant(@RequestBody Tenant o) {
		Long num=tenantMapper.countTenant(o);

		return new AjaxResult().success(num);
	}

	
	
}
